<template>
  <div class="h-full">
    <PageHeader title="评价管理" />
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <div class="table-container">
      <el-table :data="tableData" style="width: 100%" border class="cover-table">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="shopId" label="商家ID" width="100" />
        <el-table-column prop="address" label="地址" width="180" />
        <el-table-column prop="shopName" label="名称" width="120" />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="contactPhone" label="联系电话" width="120" />
        <el-table-column prop="orderType" label="订单类型" width="100">
          <template #default="scope">
            <el-tag :type="getOrderTypeTag(scope.row.orderType)">
              {{ getOrderTypeText(scope.row.orderType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="评价时间" width="160" />
        <el-table-column prop="userName" label="用户昵称" width="100" />
        <el-table-column prop="userPhone" label="手机号码" width="120" />
        <el-table-column prop="orderNumber" label="订单编号" width="150" />
        <el-table-column prop="orderAmount" label="订单支付金额" width="120">
          <template #default="scope">
            {{ scope.row.orderAmount }} 元
          </template>
        </el-table-column>
        <el-table-column label="评分" width="280">
          <template #default="scope">
            <div class="score-box">
              <div class="score-item">
                <span>口味:</span>
                <el-rate v-model="scope.row.tasteScore" disabled text-color="#ff9900" />
              </div>
              <div class="score-item">
                <span>服务:</span>
                <el-rate v-model="scope.row.serviceScore" disabled text-color="#ff9900" />
              </div>
              <div class="score-item">
                <span>性价比:</span>
                <el-rate v-model="scope.row.valueScore" disabled text-color="#ff9900" />
              </div>
              <div class="score-item">
                <span>环境:</span>
                <el-rate v-model="scope.row.environmentScore" disabled text-color="#ff9900" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评价内容" min-width="300">
          <template #default="scope">
            <div class="review-content">
              <div class="review-text">{{ scope.row.reviewContent }}</div>
              <div class="review-images" v-if="scope.row.reviewImages && scope.row.reviewImages.length > 0">
                <el-image
                  v-for="(img, index) in scope.row.reviewImages"
                  :key="index"
                  :src="img"
                  :preview-src-list="scope.row.reviewImages"
                  :initial-index="index"
                  class="review-image"
                  fit="cover"
                />
              </div>
              <div class="review-reply" v-if="scope.row.replyContent">
                <div class="reply-title">商家回复：</div>
                <div class="reply-content">{{ scope.row.replyContent }}</div>
                <div class="reply-images" v-if="scope.row.replyImages && scope.row.replyImages.length > 0">
                  <el-image
                    v-for="(img, index) in scope.row.replyImages"
                    :key="index"
                    :src="img"
                    :preview-src-list="scope.row.replyImages"
                    :initial-index="index"
                    class="reply-image"
                    fit="cover"
                  />
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleReply(scope.row)"
              v-if="!scope.row.replyContent"
            >
              回复评论
            </el-button>
            <el-button
              type="info"
              size="small"
              link
              @click="handleReply(scope.row)"
              v-else
            >
              编辑回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 评论回复对话框 -->
    <ReplyToReviewDia
      v-model="replyDialogVisible"
      :data="currentReview"
      @success="handleReplySuccess"
    />
  </div>
</template>

<script setup>
import { ref } from "vue";
import SearchCom from "@/components/searchCom.vue";
import PageHeader from "@/components/PageHeader.vue";
import ReplyToReviewDia from "./replyToReviewDia.vue";
import { ElMessage } from 'element-plus';

// 搜索配置
const searchConfig = ref([
  {
    label: "商家ID",
    key: "shopId",
    type: "input",
  },
  {
    label: "地址",
    key: "address",
    type: "input",
  },
  {
    label: "名称",
    key: "shopName",
    type: "input",
  },
  {
    label: "联系人",
    key: "contactPerson",
    type: "input",
  },
  {
    label: "联系电话",
    key: "contactPhone",
    type: "input",
  },
  {
    label: "评价时间",
    key: "timeRange",
    type: "daterange",
  },
  {
    label: "用户昵称",
    key: "userName",
    type: "input",
  },
  {
    label: "手机号码",
    key: "userPhone",
    type: "input",
  },
  {
    label: "订单编号",
    key: "orderNumber",
    type: "input",
  },
  {
    label: "订单类型",
    key: "orderType",
    type: "select",
    options: [
      { label: "全部", value: "" },
      { label: "外卖", value: "takeout" },
      { label: "点餐", value: "dining" },
      { label: "团购", value: "groupon" },
      { label: "买单", value: "payment" },
    ],
  },
]);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 回复对话框
const replyDialogVisible = ref(false);
const currentReview = ref(null);

// 模拟表格数据
const generateMockData = () => {
  return Array.from({ length: 10 }, (_, index) => {
    const orderType = ['takeout', 'dining', 'groupon', 'payment'][index % 4];
    const hasReply = index % 3 === 0;
    
    return {
      id: index + 1,
      shopId: `SH${(index % 5 + 1).toString().padStart(3, '0')}`,
      address: `北京市朝阳区建国路${88 + index}号`,
      shopName: `示例商家${index % 5 + 1}`,
      contactPerson: `联系人${index % 5 + 1}`,
      contactPhone: `1380013${(index % 5 + 1).toString().padStart(4, '0')}`,
      orderType,
      reviewTime: `2024-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')} ${(index % 24).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}`,
      userName: `用户${index + 1}`,
      userPhone: `1390013${index.toString().padStart(4, '0')}`,
      orderNumber: `ORD${Date.now().toString().slice(-8)}${index}`,
      orderAmount: (Math.random() * 300 + 50).toFixed(2),
      
      tasteScore: Math.floor(Math.random() * 3) + 3,
      serviceScore: Math.floor(Math.random() * 3) + 3,
      valueScore: Math.floor(Math.random() * 3) + 3,
      environmentScore: Math.floor(Math.random() * 3) + 3,
      
      reviewContent: [
        "菜品很好吃，服务也很周到！",
        "味道不错，就是送餐速度有点慢。",
        "性价比很高，下次还会再来！",
        "环境很好，适合朋友聚餐，就是价格有点小贵。",
        "菜品分量足，味道好，很满意。"
      ][index % 5],
      
      reviewImages: Array.from({ length: index % 4 }, () => "https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg"),
      
      replyContent: hasReply ? "感谢您的评价，我们会继续努力提供更好的服务！" : "",
      replyImages: hasReply ? Array.from({ length: index % 2 }, () => "https://img-lang.55sld.com/channel1langimages/seller/goods/FazXTfI500MzGvRhxTA.jpg") : []
    };
  });
};

const tableData = ref(generateMockData());

// 获取订单类型文本
const getOrderTypeText = (type) => {
  const typeMap = {
    'takeout': '外卖',
    'dining': '点餐',
    'groupon': '团购',
    'payment': '买单'
  };
  return typeMap[type] || '未知';
};

// 获取订单类型标签样式
const getOrderTypeTag = (type) => {
  const typeMap = {
    'takeout': 'success',
    'dining': 'primary',
    'groupon': 'warning',
    'payment': 'info'
  };
  return typeMap[type] || '';
};

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 实际项目中这里应该调用API进行搜索
  ElMessage.success('搜索请求已发送');
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info('表单已重置');
};

// 处理回复评论
const handleReply = (row) => {
  currentReview.value = { ...row };
  replyDialogVisible.value = true;
};

// 处理回复成功
const handleReplySuccess = (data) => {
  // 更新表格数据
  const index = tableData.value.findIndex(item => item.id === data.id);
  if (index !== -1) {
    tableData.value[index].replyContent = data.replyContent;
    tableData.value[index].replyImages = data.replyImages;
    ElMessage.success('回复成功');
  }
};

// 处理页码变化
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  // 这里请求对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  // 这里请求对应数量的数据
};
</script>

<style scoped lang="scss">
.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
}

.score-box {
  .score-item {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    
    span {
      width: 60px;
      text-align: right;
      margin-right: 5px;
    }
  }
}

.review-content {
  padding: 10px 0;
  
  .review-text {
    line-height: 1.5;
    margin-bottom: 10px;
  }
  
  .review-images {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 15px;
    
    .review-image {
      width: 60px;
      height: 60px;
      margin-right: 10px;
      margin-bottom: 10px;
      border-radius: 4px;
      cursor: pointer;
    }
  }
  
  .review-reply {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
    
    .reply-title {
      font-weight: bold;
      margin-bottom: 5px;
      color: #409EFF;
    }
    
    .reply-content {
      line-height: 1.5;
      margin-bottom: 10px;
    }
    
    .reply-images {
      display: flex;
      flex-wrap: wrap;
      
      .reply-image {
        width: 60px;
        height: 60px;
        margin-right: 10px;
        margin-bottom: 10px;
        border-radius: 4px;
        cursor: pointer;
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

// 适配移动端样式
@media (max-width: 768px) {
  .el-table {
    width: 100%;
    overflow-x: auto;
  }
}
</style>
